﻿using DadayunApi;
using DadayunApi.Model;
using KbtSync.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace KbtSync.DAL
{
    
    public class DadayunDAL
    {
        public FormApi formApi;
        public ReportApi reportApi;
        public BaseApi baseApi;
        public string WritingJson { get; private set; }

        public DadayunDAL(AppAuthBase authBase, string baseUri)
        {
            formApi = new FormApi(authBase, baseUri);
            reportApi = new ReportApi(authBase, baseUri);
            baseApi = new BaseApi(authBase, baseUri);
        }

        public string ResponseJosn
        {
            get
            {
                return formApi.ResponseJson;
            }
        }

        /// <summary>
        /// 获取成品仓清单
        /// </summary>
        /// <returns></returns>
        public List< IdName> GetProductWarehouses()
        {
            return baseApi.GetDictionaryItems("成品仓");
        }
        /// <summary>
        /// 获取产品清单
        /// </summary>
        /// <returns></returns>
        public IList<ProductReportResult> GetProductList()
        {
            //查询产品总量,记录在count中
            string json = reportApi.GetReportInJson("产品报价清单", out int count, EReportKeyOptions.FieldMap);
            //查询全部产品清单
            json = reportApi.GetReportInJson("产品报价清单", out count, EReportKeyOptions.FieldMap,null,0,count);            
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            else
            {
                ProductReport obj = JsonConvert.DeserializeObject<ProductReport>(json);
                //类StoreInfo的属性与搭搭云返回的字段名称不一致，在StoreInfo定义中指定搭搭云的字段名
                return obj.Results;
            }
        }
        /// <summary>
        /// 获取产品清单
        /// </summary>
        /// <returns></returns>
        public IList<ProductReportResult> GetProductList(int start, int count, out int totalCount)
        {
            string json = reportApi.GetReportInJson("产品清单", out totalCount, EReportKeyOptions.FieldMap,null, start, count);
            if (string.IsNullOrEmpty( json))
            {
                return null;
            }
            ProductReport obj = JsonConvert.DeserializeObject<ProductReport>(json);            
            return obj.Results;
        }
        /// <summary>
        /// 清除指定ERP产品代码的库存信息
        /// 方法：通过更新库存信息表的表单
        /// </summary>
        /// <param name="erpItemCode">产品编码</param>
        /// <param name="version">版本</param>
        /// <returns></returns>
        internal bool ClearStorageInfo(string erpItemCode,double version=0)
        {
            List<StorageResult> storages = GetStorageReports(erpItemCode);
            string id = storages[0].DataObjs.FormInstances[0].InstanceId;
            return false;
        }
        /// <summary>
        /// 获取CRM中的产品库存信息
        /// 未指定产品编码时，返回全部产品库存信息
        /// </summary>
        /// <param name="erpItemCode"> 获取指定ERP产品代码的库存信息,缺省获取所有库存</param>
        /// <param name="version">产品版本</param>
        /// <returns></returns>
        internal List<StorageResult> GetStorageReports(string erpItemCode="",double version=0)
        {
           
            ReportFilter[] filter = new ReportFilter[2];
            filter[0] = new ReportFilter
            {
                Name = "ERP编码",
                Operator = "=",
                DestValue = erpItemCode
            };
            filter[1] = new ReportFilter
            {
                Name = "版本",
                Operator = "=",
                DestValue = version.ToString()
            };
            reportApi.GetReportInJson("产品库存报表", out int totalCount, EReportKeyOptions.ColName, filter,0,1);//获取数据总量
            string json= reportApi.GetReportInJson("产品库存报表", out totalCount,EReportKeyOptions.ColName,filter,0,totalCount);
            if (json.Length<15) return null;
            StorageReport obj = JsonConvert.DeserializeObject<StorageReport>(json);
            
            return obj.Results;
        }
       
        /// <summary>
        /// 创建一个库存信息表单实例
        /// </summary>
        /// <param name="storageForm"></param>
        /// <returns></returns>
        public HttpStatusCode CreateStorageForm(StorageForm storageForm)
        {
            string formData = JsonConvert.SerializeObject(storageForm);
            HttpStatusCode ans = formApi.CreateFormInstance("StorageForm", formData, out string instanceId, true, EAutoFillMode.ForceAll, EKeyOptions.Entity, false);
            if (ans==HttpStatusCode.Created)
            {
                storageForm = JsonConvert.DeserializeObject<StorageForm>(formApi.ResponseJson);
            }
            return ans;
        }
        /// <summary>
        /// 批量处理存储信息表
        /// </summary>
        /// <param name="storageForms">存储信息表实例清单.如果ID为空,则为新增,如果已有ID,则为更新</param>
        /// <param name="count">返回更新的产品数量</param>
        /// <returns></returns>
        public HttpStatusCode BatchProceed(List<StorageForm> storageForms,out int count)
        {
            count = 0;
            List<BatchInstance> instances = new List<BatchInstance>();
            foreach (var f in storageForms)
            {
                BatchInstance b = new BatchInstance
                {                    
                    TplIdOrName = "StorageForm",
                    InstanceId = f.Id,
                    InstanceData = f,
                    //AutoFillMode = EAutoFillMode.ForceAll.ToString(),
                };
                if( string.IsNullOrEmpty(f.Id))
                {
                    b.InstanceId = Guid.NewGuid().ToString();
                    //f.Id = b.InstanceId;
                    b.Action = EActions.Create.ToString();
                }
                else
                {
                    b.Action = EActions.Update.ToString();
                }
                instances.Add(b);
            }
            //var ans= ddyApi.FormBatchProcessing(instances, out BatchInstance[] Respinstances, EKeyOptions.Entity);
#if DEBUG
            WritingJson = JsonConvert.SerializeObject(instances);
#endif
            HttpStatusCode ans = formApi.FormBatchProcessingRestSharp(instances, out BatchInstance[] Respinstances, EKeyOptions.Entity);
            if (ans == HttpStatusCode.OK) count = Respinstances.Length;
            return ans;
        }

        public DateTime GetServerTime()
        {
           return baseApi.GetServerTime();
        }

        /// <summary>
        /// 修改库存信息表单实例
        /// </summary>
        /// <param name="instanceId">要修改的实例ID</param>
        /// <param name="storageForm">要修改的表单数据。如果要修改子表数据，则需要给出子表的InstanceId</param>
        /// <returns></returns>
        public HttpStatusCode EditStorageForm(string instanceId, StorageForm storageForm)
        {
            string formData = JsonConvert.SerializeObject(storageForm);
            var ans = formApi.EditFormInstance("StorageForm", instanceId, formData, true, EAutoFillMode.ForceAll, EKeyOptions.Entity,false);
            return ans;
            
        }
        /// <summary>
        /// 获取库存表单实例
        /// </summary>
        /// <param name="idOrName">表单Id或名称或Entity</param>
        /// <param name="instanceId">实例ID</param>
        /// <param name="keyOption"></param>
        /// <returns></returns>
        public StorageForm GetStorageForm(string instanceId)
        {
            string idOrName = "StorageForm";
            EKeyOptions keyOption = EKeyOptions.Entity;
            var ans = formApi.GetFormInstance(idOrName, instanceId, keyOption,false);
            return JsonConvert.DeserializeObject<StorageForm>(ans); 
            
        }
        
       
        /// <summary>
        /// 获取某表单模板的的所有实例信息
        /// </summary>
        /// <param name="idOrName">表单Id或名称或Entity</param>
        /// <param name="totalCount">输出：总条数</param>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <param name="sortField"></param>
        /// <param name="filter">查询条件json字符串。</param>
        /// <param name="keyOption"></param>
        /// <returns></returns>
        public List<FormInstanceInfo> GetFormList(string idOrName, out int totalCount, int start = 0, int limit = 20, string sortField = "-CreateTime", FormFilter[] filter = null, EKeyOptions keyOption = EKeyOptions.FieldName)
        {
            return formApi.GetFormList(idOrName, out totalCount, start, limit, sortField, filter, keyOption);
        }
    }
}
